package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//@ControllerAdvice : 指定拦截那些类型的控制器;
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//@ResponseBody: 将方法的返回值 R 对象转换为json格式的数据, 响应给页面;
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
     log.info(ex.getMessage());
     if(ex.getMessage().contains("Duplicate entry")){
         String[] s = ex.getMessage().split(" ");
         String msg = s[2]+"已存在";
         return R.error(msg);
     }
        return R.error("未知错误...");
    }

    /**
     * 捕获我们自定义的异常 CustomException
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());

    }
}
